package com.beerandjesus.sportofkings.handicapper.profile.resolver;

import com.beerandjesus.sportofkings.handicapper.model.Workout;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.Horse;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.HorseRace;
import com.beerandjesus.sportofkings.handicapper.profile.AnalysisProfile;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static com.beerandjesus.sportofkings.handicapper.profile.AnalysisProfile.Type.*;
import static com.beerandjesus.sportofkings.handicapper.profile.AnalysisProfileBuilder.analysisProfile;

/**
 * Date: 7/4/13
 * Time: 10:40 AM
 */
public class ConsistentWorkoutsProfileResolver implements AnalysisProfileResolver {
    private final Work NO_MATCH = new Work("nomatch", "nomatch");

    public AnalysisProfile resolve(HorseRace race, Horse horse) {
        // Must have last 2 out of 3 workouts at exactly equal distance and time
        List<Workout> works = horse.getWorkouts();
        if (works == null || works.size() < 2) {
            return null;
        }
        List<Work> workouts = new ArrayList<Work>();
        List<Workout> lastThreeWorkouts = works.subList(0, Math.min(works.size(), 3));
        for (Workout work : lastThreeWorkouts) {
            String distance = work.getDistance();
            String time = work.getTime();
            // Missing data nixes profile
            if (StringUtils.isEmpty(distance) || StringUtils.isEmpty(time)) {
                return null;
            }
            workouts.add(new Work(distance.trim(), time.trim()));
        }
        Work first = workouts.get(0);
        Work second = workouts.get(1);
        Work third = workouts.size() == 3 ? workouts.get(2) : NO_MATCH;
        if (first.equals(second) || second.equals(third) || (first.equals(third)) && !second.isEqualDistance(first)) {
            return analysisProfile(CONSISTENT_WORKOUTS, 1);
        }
        return null;
    }
    private class Work {
        private String time;
        private String distance;

        private Work(String distance, String time) {
            this.time = time;
            this.distance = distance;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Work work = (Work) o;

            return distance.equals(work.distance) && time.equals(work.time);

        }

        @Override
        public int hashCode() {
            int result = time.hashCode();
            result = 31 * result + distance.hashCode();
            return result;
        }

        public boolean isEqualDistance(Work work) {
            return this.distance.equals(work.distance);
        }
    }
}
